home *** CD-ROM | disk | FTP | other *** search
/ Over 1,000 Windows 95 Programs / Over 1000 Windows 95 Programs (Microforum) (Disc 1).iso / 0957 / gnugrep / cl / search.c < prev   
Encoding:
C/C++ Source or Header  |  1996-06-27  |  11.4 KB  |  425 lines

  1. /* search.c - searching subroutines using dfa, kwset and regex for grep.
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written August 1992 by Mike Haertel. */
  19.  
  20. #include <ctype.h>
  21. #include <limits.h>
  22. #include <stdlib.h>
  23. #include <sys/types.h>
  24. #include <string.h>
  25. #include <memory.h>
  26.  
  27. #define bcopy(s, d, n) memcpy((d), (s), (n))
  28. #define ISALNUM(C) (isascii(C) && isalnum(C))
  29. #define ISUPPER(C) (isascii(C) && isupper(C))
  30.  
  31. #define TOLOWER(C) (ISUPPER(C) ? tolower(C) : (C))
  32.  
  33. #include "grep.h"
  34. #include "dfa.h"
  35. #include "kwset.h"
  36. #include "regex.h"
  37.  
  38. #define NCHAR (UCHAR_MAX + 1)
  39.  
  40. static void Gcompile(char *, size_t);
  41. static void Ecompile(char *, size_t);
  42. static char *EGexecute(char *, size_t, char **);
  43. static void Fcompile(char *, size_t);
  44. static char *Fexecute(char *, size_t, char **);
  45.  
  46. /* Here is the matchers vector for the main program. */
  47. struct matcher matchers[] = {
  48.   { "default", Gcompile, EGexecute },
  49.   { "grep", Gcompile, EGexecute },
  50.   { "ggrep", Gcompile, EGexecute },
  51.   { "egrep", Ecompile, EGexecute },
  52.   { "posix-egrep", Ecompile, EGexecute },
  53.   { "gegrep", Ecompile, EGexecute },
  54.   { "fgrep", Fcompile, Fexecute },
  55.   { "gfgrep", Fcompile, Fexecute },
  56.   { 0, 0, 0 },
  57. };
  58.  
  59. /* For -w, we also consider _ to be word constituent.  */
  60. #define WCHAR(C) (ISALNUM(C) || (C) == '_')
  61.  
  62. /* DFA compiled regexp. */
  63. static struct dfa dfa;
  64.  
  65. /* Regex compiled regexp. */
  66. static struct re_pattern_buffer regex;
  67.  
  68. /* KWset compiled pattern.  For Ecompile and Gcompile, we compile
  69.    a list of strings, at least one of which is known to occur in
  70.    any string matching the regexp. */
  71. static kwset_t kwset;
  72.  
  73. /* Last compiled fixed string known to exactly match the regexp.
  74.    If kwsexec() returns < lastexact, then we don't need to
  75.    call the regexp matcher at all. */
  76. static int lastexact;
  77.  
  78. void dfaerror(char *mesg)
  79. //-----------------------
  80. {
  81.   fatal(mesg, 0);
  82. }
  83.  
  84. static void kwsinit()
  85. //-------------------
  86. {
  87.   static char trans[NCHAR];
  88.   int i;
  89.  
  90.   if (match_icase)
  91.     for (i = 0; i < NCHAR; ++i)
  92.       trans[i] = TOLOWER(i);
  93.  
  94.   if (!(kwset = kwsalloc(match_icase ? trans : (char *) 0)))
  95.     fatal("memory exhausted", 0);
  96. }  
  97.  
  98. /* If the DFA turns out to have some set of fixed strings one of
  99.    which must occur in the match, then we build a kwset matcher
  100.    to find those strings, and thus quickly filter out impossible
  101.    matches. */
  102. static void kwsmusts()
  103. //--------------------
  104. {
  105.   struct dfamust *dm;
  106.   char *err;
  107.  
  108.   if (dfa.musts)
  109.     {
  110.       kwsinit();
  111.       /* First, we compile in the substrings known to be exact
  112.      matches.  The kwset matcher will return the index
  113.      of the matching string that it chooses. */
  114.       for (dm = dfa.musts; dm; dm = dm->next)
  115.     {
  116.       if (!dm->exact)
  117.         continue;
  118.       ++lastexact;
  119.       if ((err = kwsincr(kwset, dm->must, strlen(dm->must))) != 0)
  120.         fatal(err, 0);
  121.     }
  122.       /* Now, we compile the substrings that will require
  123.      the use of the regexp matcher.  */
  124.       for (dm = dfa.musts; dm; dm = dm->next)
  125.     {
  126.       if (dm->exact)
  127.         continue;
  128.       if ((err = kwsincr(kwset, dm->must, strlen(dm->must))) != 0)
  129.         fatal(err, 0);
  130.     }
  131.       if ((err = kwsprep(kwset)) != 0)
  132.     fatal(err, 0);
  133.     }
  134. }
  135.  
  136. static void Gcompile(char *pattern, size_t size)
  137. //-----------------------------------------------
  138. {
  139.   const char *err;
  140.  
  141.   re_set_syntax(RE_SYNTAX_GREP | RE_HAT_LISTS_NOT_NEWLINE);
  142.   dfasyntax(RE_SYNTAX_GREP | RE_HAT_LISTS_NOT_NEWLINE, match_icase);
  143.  
  144.   if ((err = re_compile_pattern(pattern, size, ®ex)) != 0)
  145.     fatal(err, 0);
  146.  
  147.   dfainit(&dfa);
  148.  
  149.   /* In the match_words and match_lines cases, we use a different pattern
  150.      for the DFA matcher that will quickly throw out cases that won't work.
  151.      Then if DFA succeeds we do some hairy stuff using the regex matcher
  152.      to decide whether the match should really count. */
  153.   if (match_words || match_lines)
  154.     {
  155.       /* In the whole-word case, we use the pattern:
  156.      (^|[^A-Za-z_])(userpattern)([^A-Za-z_]|$).
  157.      In the whole-line case, we use the pattern:
  158.      ^(userpattern)$.
  159.      BUG: Using [A-Za-z_] is locale-dependent!  */
  160.  
  161.       char *n = malloc(size + 50);
  162.       int i = 0;
  163.  
  164.       strcpy(n, "");
  165.  
  166.       if (match_lines)
  167.     strcpy(n, "^\\(");
  168.       if (match_words)
  169.     strcpy(n, "\\(^\\|[^0-9A-Za-z_]\\)\\(");
  170.  
  171.       i = strlen(n);
  172.       bcopy(pattern, n + i, size);
  173.       i += size;
  174.  
  175.       if (match_words)
  176.     strcpy(n + i, "\\)\\([^0-9A-Za-z_]\\|$\\)");
  177.       if (match_lines)
  178.     strcpy(n + i, "\\)$");
  179.  
  180.       i += strlen(n + i);
  181.       dfacomp(n, i, &dfa, 1);
  182.     }
  183.   else
  184.     dfacomp(pattern, size, &dfa, 1);
  185.  
  186.   kwsmusts();
  187. }
  188.  
  189. static void Ecompile(char *pattern, size_t size)
  190. //----------------------------------------------
  191. { const char *err;
  192.  
  193.   if (strcmp(matcher, "posix-egrep") == 0)
  194.     {
  195.       re_set_syntax(RE_SYNTAX_POSIX_EGREP);
  196.       dfasyntax(RE_SYNTAX_POSIX_EGREP, match_icase);
  197.     }
  198.   else
  199.     {
  200.       re_set_syntax(RE_SYNTAX_EGREP);
  201.       dfasyntax(RE_SYNTAX_EGREP, match_icase);
  202.     }
  203.  
  204.   if ((err = re_compile_pattern(pattern, size, ®ex)) != 0)
  205.     fatal(err, 0);
  206.  
  207.   dfainit(&dfa);
  208.  
  209.   /* In the match_words and match_lines cases, we use a different pattern
  210.      for the DFA matcher that will quickly throw out cases that won't work.
  211.      Then if DFA succeeds we do some hairy stuff using the regex matcher
  212.      to decide whether the match should really count. */
  213.   if (match_words || match_lines)
  214.     {
  215.       /* In the whole-word case, we use the pattern:
  216.      (^|[^A-Za-z_])(userpattern)([^A-Za-z_]|$).
  217.      In the whole-line case, we use the pattern:
  218.      ^(userpattern)$.
  219.      BUG: Using [A-Za-z_] is locale-dependent!  */
  220.  
  221.       char *n = malloc(size + 50);
  222.       int i = 0;
  223.  
  224.       strcpy(n, "");
  225.  
  226.       if (match_lines)
  227.     strcpy(n, "^(");
  228.       if (match_words)
  229.     strcpy(n, "(^|[^0-9A-Za-z_])(");
  230.  
  231.       i = strlen(n);
  232.       bcopy(pattern, n + i, size);
  233.       i += size;
  234.  
  235.       if (match_words)
  236.     strcpy(n + i, ")([^0-9A-Za-z_]|$)");
  237.       if (match_lines)
  238.     strcpy(n + i, ")$");
  239.  
  240.       i += strlen(n + i);
  241.       dfacomp(n, i, &dfa, 1);
  242.     }
  243.   else
  244.     dfacomp(pattern, size, &dfa, 1);
  245.  
  246.   kwsmusts();
  247. }
  248.  
  249. static char *EGexecute(char *buf, size_t size, char **endp)
  250. //---------------------------------------------------------
  251. { register char *buflim, *beg, *end, save;
  252.   int backref, start, len;
  253.   struct kwsmatch kwsm;
  254.   static struct re_registers regs; /* This is static on account of a BRAIN-DEAD
  255.                     Q@#%!# library interface in regex.c.  */
  256.  
  257.   buflim = buf + size;
  258.  
  259.   for (beg = end = buf; end < buflim; beg = end + 1)
  260.     {
  261.       if (kwset)
  262.     {
  263.       /* Find a possible match using the KWset matcher. */
  264.       beg = kwsexec(kwset, beg, buflim - beg, &kwsm);
  265.       if (!beg)
  266.         goto failure;
  267.       /* Narrow down to the line containing the candidate, and
  268.          run it through DFA. */
  269.       end = memchr(beg, '\n', buflim - beg);
  270.       if (!end)
  271.         end = buflim;
  272.       while (beg > buf && beg[-1] != '\n')
  273.         --beg;
  274.       save = *end;
  275.       if (kwsm.index < lastexact)
  276.         goto success;
  277.       if (!dfaexec(&dfa, beg, end, 0, (int *) 0, &backref))
  278.         {
  279.           *end = save;
  280.           continue;
  281.         }
  282.       *end = save;
  283.       /* Successful, no backreferences encountered. */
  284.       if (!backref)
  285.         goto success;
  286.     }
  287.       else
  288.     {
  289.       /* No good fixed strings; start with DFA. */
  290.       save = *buflim;
  291.       beg = dfaexec(&dfa, beg, buflim, 0, (int *) 0, &backref);
  292.       *buflim = save;
  293.       if (!beg)
  294.         goto failure;
  295.       /* Narrow down to the line we've found. */
  296.       end = memchr(beg, '\n', buflim - beg);
  297.       if (!end)
  298.         end = buflim;
  299.       while (beg > buf && beg[-1] != '\n')
  300.         --beg;
  301.       /* Successful, no backreferences encountered! */
  302.       if (!backref)
  303.         goto success;
  304.     }
  305.       /* If we've made it to this point, this means DFA has seen
  306.      a probable match, and we need to run it through Regex. */
  307.       regex.not_eol = 0;
  308.       if ((start = re_search(®ex, beg, end - beg, 0, end - beg, ®s)) >= 0)
  309.     {
  310.       len = regs.end[0] - start;
  311.       if (!match_lines && !match_words || match_lines && len == end - beg)
  312.         goto success;
  313.       /* If -w, check if the match aligns with word boundaries.
  314.          We do this iteratively because:
  315.          (a) the line may contain more than one occurence of the pattern, and
  316.          (b) Several alternatives in the pattern might be valid at a given
  317.          point, and we may need to consider a shorter one to find a word
  318.          boundary. */
  319.       if (match_words)
  320.         while (start >= 0)
  321.           {
  322.         if ((start == 0 || !WCHAR(beg[start - 1]))
  323.             && (len == end - beg || !WCHAR(beg[start + len])))
  324.           goto success;
  325.         if (len > 0)
  326.           {
  327.             /* Try a shorter length anchored at the same place. */
  328.             --len;
  329.             regex.not_eol = 1;
  330.             len = re_match(®ex, beg, start + len, start, ®s);
  331.           }
  332.         if (len <= 0)
  333.           {
  334.             /* Try looking further on. */
  335.             if (start == end - beg)
  336.               break;
  337.             ++start;
  338.             regex.not_eol = 0;
  339.             start = re_search(®ex, beg, end - beg,
  340.                       start, end - beg - start, ®s);
  341.             len = regs.end[0] - start;
  342.           }
  343.           }
  344.     }
  345.     }
  346.  
  347.  failure:
  348.   return 0;
  349.  
  350.  success:
  351.   *endp = end < buflim ? end + 1 : end;
  352.   return beg;
  353. }
  354.  
  355. static void Fcompile(char *pattern, size_t size)
  356. //----------------------------------------------
  357. { char *beg, *lim, *err;
  358.  
  359.   kwsinit();
  360.   beg = pattern;
  361.   do
  362.     {
  363.       for (lim = beg; lim < pattern + size && *lim != '\n'; ++lim)
  364.     ;
  365.       if ((err = kwsincr(kwset, beg, lim - beg)) != 0)
  366.     fatal(err, 0);
  367.       if (lim < pattern + size)
  368.     ++lim;
  369.       beg = lim;
  370.     }
  371.   while (beg < pattern + size);
  372.  
  373.   if ((err = kwsprep(kwset)) != 0)
  374.     fatal(err, 0);
  375. }
  376.  
  377. static char *Fexecute(char *buf, size_t size, char **endp)
  378. //--------------------------------------------------------
  379. { register char *beg, *try, *end;
  380.   register size_t len;
  381.   struct kwsmatch kwsmatch;
  382.  
  383.   for (beg = buf; beg <= buf + size; ++beg)
  384.     {
  385.       if (!(beg = kwsexec(kwset, beg, buf + size - beg, &kwsmatch)))
  386.     return 0;
  387.       len = kwsmatch.size[0];
  388.       if (match_lines)
  389.     {
  390.       if (beg > buf && beg[-1] != '\n')
  391.         continue;
  392.       if (beg + len < buf + size && beg[len] != '\n')
  393.         continue;
  394.       goto success;
  395.     }
  396.       else if (match_words)
  397.     for (try = beg; len && try;)
  398.       {
  399.         if (try > buf && WCHAR((unsigned char) try[-1]))
  400.           break;
  401.         if (try + len < buf + size && WCHAR((unsigned char) try[len]))
  402.           {
  403.         try = kwsexec(kwset, beg, --len, &kwsmatch);
  404.         len = kwsmatch.size[0];
  405.           }
  406.         else
  407.           goto success;
  408.       }
  409.       else
  410.     goto success;
  411.     }
  412.  
  413.   return 0;
  414.  
  415.  success:
  416.   if ((end = memchr(beg + len, '\n', (buf + size) - (beg + len))) != 0)
  417.     ++end;
  418.   else
  419.     end = buf + size;
  420.   *endp = end;
  421.   while (beg > buf && beg[-1] != '\n')
  422.     --beg;
  423.   return beg;
  424. }
  425.